package com.chookss.home.knowledge;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.DiretoryEntity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BuildDirectoryActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.topFlowLayout)
    RecyclerView topFlowLayout;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.llDelete)
    LinearLayout llDelete;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    @BindView(R.id.flowLayout2)
    FlowLayout flowLayout2;
    private TitleAdapter titleAdapter;
    private ArrayList<String> nameList = new ArrayList<>();//组织排列
    private List<DiretoryEntity.UpdateRoleBean> updateRoleBeanList= new ArrayList<>();
    private List<DiretoryEntity.ViewRoleBean> viewRoleBeanList = new ArrayList<>();
    private FlowAdapter adapter;
    private FlowAdapter2 adapter2;
    private String parentCode, catalogType,catalogName,catalogCode;
    private int type=0;//0新建文件夹1修改

    @Override
    protected void onCreate(@Nullable Bundle savedInstaasfnceState) {
        super.onCreate(savedInstaasfnceState);
        setContentView(R.layout.activity_build_diretory);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState3();
        type=getIntent().getIntExtra("type",0);
        parentCode = getIntent().getStringExtra("parentCode");
        catalogCode = getIntent().getStringExtra("catalogCode");
        catalogType = getIntent().getStringExtra("catalogType");
        catalogName = getIntent().getStringExtra("catalogName");
        Utils.setEditTextInputSpeChat(edContent);
        ArrayList<String> nameLists = getIntent().getStringArrayListExtra("nameList");
        if (nameLists != null) {
            nameList.addAll(nameLists);
        }
        if (nameList.size() > 0) {
            titleAdapter = new TitleAdapter(R.layout.item_diretory_name_list, this, nameList);
            LinearLayoutManager lm = new LinearLayoutManager(this);
            lm.setOrientation(LinearLayoutManager.HORIZONTAL);
            topFlowLayout.setLayoutManager(lm);
            topFlowLayout.setAdapter(titleAdapter);
            topFlowLayout.setVisibility(View.VISIBLE);
        } else {
            topFlowLayout.setVisibility(View.GONE);
        }
        if(type==0){
            commonTitleTxt.setText("新建文件夹");
        }else{
            commonTitleTxt.setText("修改文件夹");
            edContent.setText(catalogName);
        }
        edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
              if(Utils.isNull(s.toString())){
                  llDelete.setVisibility(View.GONE);
              }else{
                  llDelete.setVisibility(View.VISIBLE);
              }
            }
        });
        getCatalogConfig();
    }

    private void addCatalogInfo() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("parentCode", parentCode);
        allmap.put("catalogType", catalogType);
        allmap.put("catalogName", edContent.getText().toString());
        String url="";
        if(type==0){
            url=Urls.addCatalogInfo;
        }else{
            url=Urls.updateCatalogInfo;
            allmap.put("catalogCode", catalogCode);
        }
        MyHttpRequest.getDefault().postRequestCompat(null, url, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    if(type==0){
                       MyToast.show("新建成功");
                    }else{
                        MyToast.show("修改成功");
                    }
                    EventBus.getDefault().post(new MyEvent("RefreshDirectory"));
                    finish();
                } else {
                    MyToast.show(reObject.getString("msg"));
                }
            }
            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getCatalogConfig() {
        Map<String, String> allmap = new HashMap<>();
        if(type==0){
            allmap.put("catalogCode", parentCode);
        }else{
            allmap.put("catalogCode", catalogCode);
        }
        allmap.put("catalogType", catalogType);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DiretoryEntity>>() {
        }.getType(), null, Urls.getCatalogConfig, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<DiretoryEntity>() {
            @Override
            public void onSuccess(DiretoryEntity data) {
                if (data != null) {
                    updateRoleBeanList.addAll(data.getUpdateRole());
                    for (int i = 0; i <updateRoleBeanList.size() ; i++) {
                        DiretoryEntity.ViewRoleBean viewRoleBean=new  DiretoryEntity.ViewRoleBean();
                        viewRoleBean.setRoleName(updateRoleBeanList.get(i).getRoleName());
                        viewRoleBeanList.add(viewRoleBean);
                    }
                    viewRoleBeanList.addAll(data.getViewRole());
                    adapter = new FlowAdapter(BuildDirectoryActivity.this, updateRoleBeanList);
                    flowLayout.setAdapter(adapter);
                    adapter2 = new FlowAdapter2(BuildDirectoryActivity.this, viewRoleBeanList);
                    flowLayout2.setAdapter(adapter2);
                    flowLayout.setVisibility(View.VISIBLE);
                    flowLayout2.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    class TitleAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Activity context;

        public TitleAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView tvItemTitle = helper.getView(R.id.tvTitle);
            ImageView ivArrow = helper.getView(R.id.ivArrow);
            tvItemTitle.setText(entity);
            if (helper.getItemPosition() > 0) {
                ivArrow.setVisibility(View.VISIBLE);
            } else {
                ivArrow.setVisibility(View.GONE);
            }
            if (helper.getItemPosition() == nameList.size() - 1) {
                tvItemTitle.setTextColor(Color.parseColor("#333333"));
            } else {
                tvItemTitle.setTextColor(Color.parseColor("#8a8a8a"));
            }
        }
    }
    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<DiretoryEntity.UpdateRoleBean> mContentList;

        public FlowAdapter(Context mContext, List<DiretoryEntity.UpdateRoleBean> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_diretory_name, parent, false);
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            mlp.setMargins(0, 0, Utils.dip2px(mContext, 12), Utils.dip2px(mContext, 12));
            view.setLayoutParams(mlp);
            return new FlowAdapter.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position).getRoleName());
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
            }
        }
    }
    class FlowAdapter2 extends FlowLayout.Adapter<FlowAdapter2.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<DiretoryEntity.ViewRoleBean> mContentList;

        public FlowAdapter2(Context mContext, List<DiretoryEntity.ViewRoleBean> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter2.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_diretory_name, parent, false);
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            mlp.setMargins(0, 0, Utils.dip2px(mContext, 12), Utils.dip2px(mContext, 12));
            view.setLayoutParams(mlp);
            return new FlowAdapter2.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter2.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position).getRoleName());
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
            }
        }
    }
    @OnClick({R.id.common_title_back, R.id.llDelete, R.id.tv_publish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llDelete:
                edContent.setText("");
                break;
            case R.id.tv_publish:
                if(Utils.isNull(edContent.getText().toString())){
                    MyToast.show("请输入文件夹名称");
                }else{
                    addCatalogInfo();
                }
                break;
        }
    }
}
